//
//  DBCameraView.m
//  DBCamera
//
//  Created by iBo on 31/01/14.
//  Copyright (c) 2014 PSSD - Daniele Bogo. All rights reserved.
//

#import "DBCameraView.h"
#import "DBCameraMacros.h"

#define previewFrameRetina (CGRect){ 0, 65, 320, 350 }
#define previewFrameRetina_4 (CGRect){ 0, 65, 320, 425 }

@interface DBCameraView ()
{
    UIView *topView;
    UIView *bottomView;
    UIView *midView;
}
@property (nonatomic, strong) CALayer *focusBox, *exposeBox;
@property (nonatomic, strong) UIButton *triggerButton, *cameraButton, *flashButton, *closeButton ,*ruleBtn;
@end

@implementation DBCameraView

+ (id) initWithFrame:(CGRect)frame
{
    return [[self alloc] initWithFrame:frame captureSession:nil];
}

+ (DBCameraView *) initWithCaptureSession:(AVCaptureSession *)captureSession
{
    return [[self alloc] initWithFrame:[[UIScreen mainScreen] bounds] captureSession:captureSession];
}

- (id) initWithFrame:(CGRect)frame captureSession:(AVCaptureSession *)captureSession
{
    self = [super initWithFrame:frame];
    
    if ( self ) {
  [self setBackgroundColor:BackPurColor];
//        midView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60.0f)];//顶部的宽度
//        mid.backgroundColor = BackPurColor;
//        [self addSubview:topView];
        _previewLayer = [[AVCaptureVideoPreviewLayer alloc] init];
//        if ( captureSession ) {
            [_previewLayer setSession:captureSession];
//            [_previewLayer setFrame: IS_RETINA_4 ? previewFrameRetina_4 : previewFrameRetina ];
            _previewLayer.frame = CGRectMake(0, 60, kScreenWidth, kScreenHeight - 60 - [UIView getHeight:78.0f]);
//        } else{
//            [_previewLayer setFrame:self.bounds];
//        }
        if ( [_previewLayer respondsToSelector:@selector(connection)] ) {
            if ( [_previewLayer.connection isVideoOrientationSupported] )
                [_previewLayer.connection setVideoOrientation:AVCaptureVideoOrientationPortrait];
        }
        
        [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
        
        [self.layer insertSublayer:_previewLayer atIndex:0];
    }
    
    return self;
}

- (void) defaultInterface
{
    [self.layer addSublayer:self.focusBox];
    [self.layer addSublayer:self.exposeBox];//tap的layer效果 加在了self。layer 上 原本加在_previewlayer 上 但是previewlayer scale 变大 其相对self.view的就改变了位置。
    
    UIView *stripe = [[UIView alloc] initWithFrame:(CGRect){ CGRectGetMidX(self.bounds) - 40, CGRectGetMaxY(_previewLayer.frame) , 80, 80 }]; //拍摄按钮的 背景阴影
    [stripe setBackgroundColor:RGBColor(0x000000, .5f)];
    [stripe.layer setCornerRadius:40.0f];
    [self addSubview:stripe];
    
    topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64.0f)];//顶部的宽度
    topView.backgroundColor = BackPurColor;
    [self addSubview:topView];
    
    bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - [UIView getHeight:78.0f], kScreenWidth, [UIView getHeight:78.0f])];//底部的宽度
    bottomView.backgroundColor = BackPurColor;
    [self addSubview:bottomView];
    
    [topView addSubview:self.cameraButton];
    [topView addSubview:self.flashButton];
    
    [bottomView addSubview:self.triggerButton];
     [bottomView addSubview:self.closeButton];
    if (!self.isHaveRuleBtn) {
        [bottomView addSubview:self.ruleBtn];
    }
    CGPoint tempPoint = CGPointMake(kScreenWidth / 2.0f, kScreenHeight / 2.0f);
    if ( [_delegate respondsToSelector:@selector(cameraView:focusAtPoint:)] && CGRectContainsPoint(_previewLayer.frame, tempPoint) )
        [_delegate cameraView:self focusAtPoint:(CGPoint){ tempPoint.x, tempPoint.y}];
    
    [self createGesture];
}

#pragma mark - Buttons

- (UIButton *) triggerButton
{
    if ( !_triggerButton ) {
        _triggerButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _triggerButton.backgroundColor = [UIColor clearColor];
//        [_triggerButton setBackgroundColor:[UIColor whiteColor]];
//        [_triggerButton setImage:[UIImage imageNamed:@"Btn_Normal_Paizhao1.png"] forState:UIControlStateNormal];
        [_triggerButton setBackgroundImage:[UIImage imageNamed:@"Btn_Normal_Paizhao1.png"] forState:UIControlStateNormal];
        CGFloat btnWW = [UIView getHeight:55.0f];
     
        _triggerButton.frame = CGRectMake( bottomView.width / 2.0f - btnWW/2.0f, bottomView.height /2.0f - btnWW / 2.0f, btnWW, btnWW);
        [_triggerButton.layer setCornerRadius:35.0f];
//        _triggerButton.layer.shouldRasterize = YES;//光栅重用
        [_triggerButton addTarget:self action:@selector(triggerAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _triggerButton;
}
- (UIButton *)ruleBtn
{
    _ruleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    _ruleBtn.backgroundColor = [UIColor whiteColor];
//    [_ruleBtn setImage:[UIImage imageNamed:@"Btn_Normal_TakeBtn"] forState:UIControlStateNormal];
    [_ruleBtn setBackgroundImage:[UIImage imageNamed:@"xuanzexiangce1"] forState:UIControlStateNormal];
    _ruleBtn.frame = CGRectMake(_triggerButton.x - 70.0f, _triggerButton.centerY - 25.0f / 2.0f, 25.0f, 25.0f);
    [_ruleBtn addTarget:self action:@selector(clickToRuleView) forControlEvents:UIControlEventTouchUpInside];
    return _ruleBtn;
}
- (UIButton *) closeButton
{
    if ( !_closeButton ) {
        _closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeButton setBackgroundColor:[UIColor clearColor]];
//        [_closeButton setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        _closeButton.frame = CGRectMake(_triggerButton.maxX + 20, bottomView.height / 2.0f - 20, 60, 40);
        [_closeButton setTitle:@"取消" forState:UIControlStateNormal];
        _closeButton.titleLabel.font = [UIFont systemFontOfSize:16.0f];
        
        [_closeButton addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _closeButton;
}

- (UIButton *) cameraButton
{
    if ( !_cameraButton ) {
        _cameraButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_cameraButton setBackgroundColor:[UIColor clearColor]];
//        [_cameraButton setImage:[UIImage imageNamed:@"flip"] forState:UIControlStateNormal];
//        [_cameraButton setImage:[UIImage imageNamed:@"flipSelected"] forState:UIControlStateSelected];
        [_cameraButton setBackgroundImage:[UIImage imageNamed:@"paizhao"] forState:UIControlStateNormal];
        _cameraButton.frame = CGRectMake(topView.width - 45, 24.0f, 30, 30);
//        [_cameraButton setFrame:(CGRect){ 15, 17.5f, 30, 30 }];
        [_cameraButton addTarget:self action:@selector(changeCamera:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _cameraButton;
}

- (UIButton *) flashButton
{
    if ( !_flashButton ) {
        _flashButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_flashButton setBackgroundColor:[UIColor clearColor]];
//        [_flashButton setImage:[UIImage imageNamed:@"flash"] forState:UIControlStateNormal];
//        [_flashButton setImage:[UIImage imageNamed:@"flashSelected"] forState:UIControlStateSelected];
        [_flashButton setBackgroundImage:[UIImage imageNamed:@"shanguangdeng.png"] forState:UIControlStateNormal];
        _flashButton.frame = CGRectMake(15.0f, 24.0f, 30.0f, 30.0f);
//        [_flashButton setFrame:(CGRect){ topView.width - 45, 15.0f, 30, 30 }];
        [_flashButton addTarget:self action:@selector(flashTriggerAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _flashButton;
}

#pragma mark - Focus / Expose Box

- (CALayer *) focusBox
{
    if ( !_focusBox ) {
        _focusBox = [[CALayer alloc] init];
        [_focusBox setCornerRadius:40.0f];
        [_focusBox setBounds:CGRectMake(0.0f, 0.0f, 80, 80)];
        [_focusBox setBorderWidth:5.f];
        [_focusBox setBorderColor:[UIColor whiteColor].CGColor];
//        [_focusBox setBorderColor:[RGBColor(0xffffff, 1) CGColor]];
        [_focusBox setOpacity:0];
    }
    
    return _focusBox;
}

- (CALayer *) exposeBox
{
    if ( !_exposeBox ) {
        _exposeBox = [[CALayer alloc] init];
        [_exposeBox setCornerRadius:55.0f];
        [_exposeBox setBounds:CGRectMake(0.0f, 0.0f, 110, 110)];
        [_exposeBox setBorderWidth:5.f];
         [_exposeBox setBorderColor:[UIColor whiteColor].CGColor];
//        [_exposeBox setBorderColor:[RGBColor(0x00ffff, 1) CGColor]];
        [_exposeBox setOpacity:0];
    }
    
    return _exposeBox;
}

- (void) draw:(CALayer *)layer atPointOfInterest:(CGPoint)point andRemove:(BOOL)remove
{
    if ( remove )
        [layer removeAllAnimations];
    
    if ( [layer animationForKey:@"transform.scale"] == nil && [layer animationForKey:@"opacity"] == nil ) {
        [CATransaction begin];
        [CATransaction setValue: (id) kCFBooleanTrue forKey: kCATransactionDisableActions];
        [layer setPosition:point];
        layer.anchorPoint = CGPointMake(0.5, 0.5);
        [CATransaction commit];
        
        
        CABasicAnimation *scale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        [scale setFromValue:[NSNumber numberWithFloat:1]];
        [scale setToValue:[NSNumber numberWithFloat:0.7]];
        [scale setDuration:0.8];
        [scale setRemovedOnCompletion:YES];
        
        CABasicAnimation *opacity = [CABasicAnimation animationWithKeyPath:@"opacity"];
        [opacity setFromValue:[NSNumber numberWithFloat:1]];
        [opacity setToValue:[NSNumber numberWithFloat:0]];
        [opacity setDuration:0.8];
        [opacity setRemovedOnCompletion:YES];
        
        [layer addAnimation:scale forKey:@"transform.scale"];
        [layer addAnimation:opacity forKey:@"opacity"];
    }
}

- (void) drawFocusBoxAtPointOfInterest:(CGPoint)point andRemove:(BOOL)remove
{
    [self draw:_focusBox atPointOfInterest:point andRemove:remove];
}

- (void) drawExposeBoxAtPointOfInterest:(CGPoint)point andRemove:(BOOL)remove
{
    [self draw:_exposeBox atPointOfInterest:point andRemove:remove];
}

#pragma mark - Gestures

- (void) createGesture
{
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector( tapToFocus: )];
    [singleTap setNumberOfTapsRequired:1];
    [singleTap setNumberOfTouchesRequired:1];
    [self addGestureRecognizer:singleTap];
    
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector( tapToExpose: )];
    [doubleTap setNumberOfTapsRequired:2];
    [doubleTap setNumberOfTouchesRequired:1];
    [self addGestureRecognizer:doubleTap];
    
    [singleTap requireGestureRecognizerToFail:doubleTap];
    
//    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
//    [self addGestureRecognizer:pinch];
}

#pragma mark - Actions

- (void) flashTriggerAction:(UIButton *)button
{
    if ( [_delegate respondsToSelector:@selector(triggerFlashForMode:)] ) {
        [button setSelected:!button.isSelected];
        [_delegate triggerFlashForMode: button.isSelected ? AVCaptureFlashModeOn : AVCaptureFlashModeOff ];
    }
}

- (void) changeCamera:(UIButton *)button
{
    [button setSelected:!button.isSelected];
    if ( button.isSelected && self.flashButton.isSelected )
        [self flashTriggerAction:self.flashButton];
    [self.flashButton setEnabled:!button.isSelected];
    if ( [self.delegate respondsToSelector:@selector(switchCamera)] )
        [self.delegate switchCamera];
}

- (void) close
{
    if ( [_delegate respondsToSelector:@selector(closeCamera)] )
        [_delegate closeCamera];
}
- (void)clickToRuleView
{
    if ([_delegate respondsToSelector:@selector(clickToPresentRuleVC)]) {
        [_delegate clickToPresentRuleVC];
    }
}
- (void) triggerAction:(UIButton *)button
{
    if ( [_delegate respondsToSelector:@selector(cameraViewStartRecording)] )
        [_delegate cameraViewStartRecording];
}

- (void) tapToFocus:(UIGestureRecognizer *)recognizer
{
    CGPoint tempPoint = (CGPoint)[recognizer locationInView:self];
//    NSLog(@"点击的 坐标%@",NSStringFromCGPoint(tempPoint));
    if ( [_delegate respondsToSelector:@selector(cameraView:focusAtPoint:)] && CGRectContainsPoint(_previewLayer.frame, tempPoint) )
        [_delegate cameraView:self focusAtPoint:(CGPoint){ tempPoint.x, tempPoint.y}];
}

- (void) tapToExpose:(UIGestureRecognizer *)recognizer
{
    CGPoint tempPoint = (CGPoint)[recognizer locationInView:self];
    if ( [_delegate respondsToSelector:@selector(cameraView:exposeAtPoint:)] && CGRectContainsPoint(_previewLayer.frame, tempPoint) )
        [_delegate cameraView:self exposeAtPoint:(CGPoint){ tempPoint.x, tempPoint.y - CGRectGetMinY(_previewLayer.frame) }];
}

- (void)handlePinch:(UIPinchGestureRecognizer *)pinchGesture
{
//    CGPoint location
    CGFloat scale = [pinchGesture scale];//获取pinch手势的 倍数
    
//    NSLog(@"scale 111 %ld",scale);

    if ([_delegate respondsToSelector:@selector(pinchToScaleTakePhotoWithPointWith:with:)]) {
        [_delegate pinchToScaleTakePhotoWithPointWith:scale with:_previewLayer];
    }
}
@end